The name of the test file should be the name of file you are testing with _test.go appended to the end like so main_test.go . Inside your test file you the test function be prepended with the word Test like so Test and then followed by the name of the function Test_IsPrime . That entire structure would be as shown below:
package main
import "testing"
func Test_IsPrime(t *testing.T) {
result, msg := IsPrime(0)
if result != false {
t.Error("Expected false, got ", result)
}
if msg != "0 is not prime" {
t.Error("Expected '0 is not prime', got ", msg)
}
}
To run the test you can use go test . Which gives output like this:
❯ go test .
ok github.com/polyglotdev/primeapp 0.130s
You can also use go test -v . where the -v is for verbose. That output looks like this 👇🏾
❯ go test -v .
=== RUN Test_IsPrime
--- PASS: Test_IsPrime (0.00s)
PASS
ok github.com/polyglotdev/primeapp 0.121s
Table TestsTable tests are way that we can clean up our code using a struct to test multiple cases:
package main
import "testing"
func Test_IsPrime(t *testing.T) {
primeTests := []struct {
name string
testNum int
expected bool
msg string
}{
{"prime", 7, true, "7 is a prime number!"},
{"not prime", 8, false, "8 is not a prime number because it is divisible by 2!"},
{"zero", 0, false, "0 is not prime by definition!"},
{"one", 1, false, "1 is not prime by definition!"},
{"negative", -7, false, "Negative numbers are not prime by definition!"},
}
for _, tt := range primeTests {
t.Run(tt.name, func(t *testing.T) {
got, msg := IsPrime(tt.testNum)
if got != tt.expected {
t.Errorf("got %t want %t", got, tt.expected)
}
if msg != tt.msg {
t.Errorf("got %q want %q", msg, tt.msg)
}
})
}
}